import {Component, ElementRef, Input, ViewChild} from '@angular/core';
import { ProblemService } from '../../problem.service';
import { ActivatedRoute } from '@angular/router';
import { AiService } from '../../../core/ai/ai.service';
import { ChatService } from '../../../core/chat/chat.service';
import {WebSocketMessage} from '../../../core/chat/WebSocketMessage';

interface ChatMessage {
  role: 'user' | 'assistant';
  text: string;
}

@Component({
  selector: 'app-feature-panel',
  standalone: false,
  templateUrl: './feature-panel.component.html',
  styleUrl: './feature-panel.component.css'
})
export class FeaturePanelComponent {
  @Input() activeFeature: string = 'problem'; // default value
  @Input() userCode: string = '';
  problem: any;
  isLoading = false;

  // 房间聊天功能变量
  inRoom = false;
  roomId: string = '';
  roomMessage: string = '';
  userName = '';
  onlineUsers: number = 0;  // 用于存储在线人数
  userChatMessages: string[] = [];
  user_chat_messages_type: string[] = [];
  newMessage: string = '';

  //AI调用功能变量
  userInput: string = '';
  chatHistory: ChatMessage[] = [];
  @ViewChild('chatMessages') chatMessages!: ElementRef;

  constructor(private problemService: ProblemService,
              private route: ActivatedRoute,
              private aiService: AiService,
              private chatService: ChatService) {
    this.chatService.getMessages().subscribe((data: WebSocketMessage) => {
      const { type, subtype, content, codeHash, masterId , clientId, cursor} = data;

      if (type === 'chat') {
        if (subtype === 'system') {
          this.userChatMessages.push(content);
          this.user_chat_messages_type.push('system');
        } else if (subtype === 'error') {
          this.userChatMessages.push(content);
          this.user_chat_messages_type.push('error');
        } else if (subtype === 'user') {
          this.userChatMessages.push(content);
          this.user_chat_messages_type.push('user');
        } else if (subtype === 'onlineCount') {
          this.onlineUsers = Number(content);
        }
      }
    });
  }

  ngOnInit(): void {
    // 获取路由中的问题 ID 参数
    const id = +this.route.snapshot.paramMap.get('id')!;  // 使用!确保参数存在

    // 获取问题的详细信息
    this.problemService.getProblemById(id).subscribe(data => {
      this.problem = data;
    });
    const currentUser = localStorage.getItem('currentUser');
    if(currentUser) this.userName = JSON.parse(currentUser).username;
  }

  sendAIMessage(): void {
    const input = this.userInput.trim();
    if (!input) return;

    // 显示用户消息
    this.chatHistory.push({role: 'user', text: input});
    this.userInput = '';

    // 显示“AI正在输入”
    const aiMessage: ChatMessage = {role: 'assistant', text: ''};
    this.chatHistory.push(aiMessage);

    this.isLoading = true; // 👈 显示 loading

    this.aiService.streamChat({
      message: input,
    }).subscribe({
      next: (chunk: string) => {
        aiMessage.text += chunk;
        this.scrollToBottom();
      },
      error: (err) => {
        aiMessage.text = '[Error] ' + err;
        this.scrollToBottom();
        this.isLoading = false; // 👈 隐藏 loading
      },
      complete: () => {
        this.scrollToBottom();
        this.isLoading = false; // 👈 隐藏 loading
      }
    });
  }
  sendHintMessage(): void {

    // 显示用户请求提示
    this.chatHistory.push({
      role: 'user',
      text: '请给我这道题的解题思路：\n\n' + this.problem.description
    });
    this.userInput = '';

    // 显示“AI正在输入”
    const aiMessage: ChatMessage = { role: 'assistant', text: '' };
    this.chatHistory.push(aiMessage);

    this.isLoading = true;

    // 构造提示用的 prompt（控制模型行为）
    const prompt = `
      你是一个经验丰富的编程教练。请根据下面这道题，提供简洁的解题思路。不要写代码或实现细节，只提供解题分析、思路或涉及到的算法/数据结构。

      题目如下：
      """
      ${this.problem.description}
      """

      请你以中文回答，并只提供思路。
      `.trim();

    this.aiService.streamChat({
      message: prompt,
    }).subscribe({
      next: (chunk: string) => {
        aiMessage.text += chunk;
        this.scrollToBottom();
      },
      error: (err) => {
        aiMessage.text = '[Error] ' + err;
        this.scrollToBottom();
        this.isLoading = false;
      },
      complete: () => {
        this.scrollToBottom();
        this.isLoading = false;
      }
    });
  }

  sendCorrectCodeMessage(): void {
    // 1. 用户请求提示
    this.chatHistory.push({
      role: 'user',
      text: `请帮我找出以下代码的问题并修改：\n\n
\`\`\`
${this.userCode}\n\n
\`\`\`
`
    });

    // 3. AI正在输入提示
    const aiMessage: ChatMessage = { role: 'assistant', text: '' };
    this.chatHistory.push(aiMessage);
    this.isLoading = true;

    // 4. 构造用于纠错的 prompt
    const prompt = `
      你是一个资深程序员，请你帮助我检查以下代码是否有错误。你需要：

      1. 明确指出代码中存在的错误（语法或逻辑问题）
      2. 给出每个错误的修改建议
      3. 给出完整、修改后的代码版本

      请使用以下格式输出：

      1. 错误描述：
      （简洁列出所有错误）

      2. 修改建议：
      （逐条列出修改思路）

      3. 修改后代码：
      （贴出完整、修改后的代码）

      请使用中文回答。以下是代码：
\`\`\`
${this.userCode}
\`\`\`
`.trim();


    // 5. 发起 AI 流式请求
    this.aiService.streamChat({
      message: prompt,
    }).subscribe({
      next: (chunk: string) => {
        aiMessage.text += chunk;
        this.scrollToBottom();
      },
      error: (err) => {
        aiMessage.text = '[Error] ' + err;
        this.scrollToBottom();
        this.isLoading = false;
      },
      complete: () => {
        this.scrollToBottom();
        this.isLoading = false;
      }
    });
  }


  private scrollToBottom(): void {
    setTimeout(() => {
      const el = this.chatMessages?.nativeElement;
      el.scrollTop = el.scrollHeight;
    }, 100);
  }

  createRoom() {
    if (!/^\d{6}$/.test(this.roomId)) {
      this.roomMessage = '请输入6位数字作为房间号';
      return;
    }
    this.chatService.createRoom(this.roomId, this.userName);
    this.roomMessage = '正在创建房间...';

    // 模拟成功回调
    setTimeout(() => {
      this.inRoom = true;
      this.roomMessage = '房间创建成功';
    }, 1000);
  }

  joinRoom() {
    if (!/^\d{6}$/.test(this.roomId)) {
      this.roomMessage = '请输入6位数字作为房间号';
      return;
    }
    this.chatService.joinRoom(this.roomId, this.userName);
    this.roomMessage = '正在加入房间...';

    // 模拟成功回调
    setTimeout(() => {
      this.inRoom = true;
      this.roomMessage = '成功加入房间';
    }, 1000);
  }

  leaveRoom() {
    this.chatService.leaveRoom();
    this.inRoom = false;
    this.roomId = '';
    this.userChatMessages = [];
    this.user_chat_messages_type = [];
    this.newMessage = '';
    this.roomMessage = '已退出房间';
  }

  sendUserMessage() {
    if (this.newMessage.trim()) {
      this.userChatMessages.push(`${this.userName}: ${this.newMessage}`);
      this.user_chat_messages_type.push('user');
      this.chatService.sendMessage(`${this.userName}: ${this.newMessage}`);
      this.newMessage = '';
    }
  }
}
